package com.stox.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.stox.converter.BeanMapper;
import com.stox.manager.CountryManager;
import com.stox.model.Country;
import com.stox.model.entity.CountryEntity;

@Controller
@RequestMapping(value="/countries")
public class CountryController implements InitializingBean{

	@Autowired
	private CountryManager countryManager;
	
	@Autowired
	private BeanMapper beanMapper;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if(0 == countryManager.count()){
			countryManager.save(new CountryEntity("IN","India","Flag_of_India.png"));
		}
	}
	
	@ResponseBody
	@Cacheable("com.stox.model.entity.CountryEntity")
	@RequestMapping(method=RequestMethod.GET, produces="application/json")
	public List<CountryEntity> findAll(){
		List<CountryEntity> countryEntities = countryManager.findAll(); 
		return beanMapper.map(countryEntities, ArrayList.class, Country.class);
	}
	
}
